package com.thinkersre.service;

import com.thinkersre.dao.elasticsearch.DiscussPostRepository;
import com.thinkersre.entity.DiscussPost;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ElasticsearchService {
    @Resource
    private DiscussPostRepository discussPostRepository;
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    public void saveDiscussPost(DiscussPost discussPost){
        discussPostRepository.save(discussPost);
    }
    public void deleteDiscussPost(int id){
        discussPostRepository.deleteById(id);
    }
    public Page<DiscussPost> searchDiscussPost(String keyword,int currentPageNo,int pageSize){






        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword,"title","content"))
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(currentPageNo,pageSize))
                .withHighlightFields(
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).build();

        return elasticsearchTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                SearchHits searchHits = searchResponse.getHits();
                if (searchHits.getTotalHits() <= 0){
                    return null;
                }

                List<DiscussPost> list = new ArrayList<>();
                for (SearchHit searchHit:searchHits){
                    //封装并返回
                    DiscussPost discussPost = new DiscussPost();

                    String id = searchHit.getSourceAsMap().get("id").toString();
                    discussPost.setId(Integer.valueOf(id));

                    String userId = searchHit.getSourceAsMap().get("userId").toString();
                    discussPost.setUserId(Integer.valueOf(userId));

                    String title = searchHit.getSourceAsMap().get("title").toString();
                    discussPost.setTitle(title);

                    String content = searchHit.getSourceAsMap().get("content").toString();
                    discussPost.setContent(content);

                    String status = searchHit.getSourceAsMap().get("status").toString();
                    discussPost.setStatus(Integer.valueOf(status));

                    String createTime = searchHit.getSourceAsMap().get("createTime").toString();
                    discussPost.setCreateTime(new Date(Long.valueOf(createTime)));

                    String commentCount = searchHit.getSourceAsMap().get("commentCount").toString();
                    discussPost.setCommentCount(Integer.valueOf(commentCount));

                    String score = searchHit.getSourceAsMap().get("score").toString();
                    discussPost.setScore(Double.valueOf(score));

                    //处理高亮显示的结果
                    HighlightField titleField = searchHit.getHighlightFields().get("title");
                    if (titleField!=null){
                        discussPost.setTitle(titleField.getFragments()[0].toString());
                    }
                    HighlightField contentField = searchHit.getHighlightFields().get("content");
                    if (contentField!=null){
                        discussPost.setContent(contentField.getFragments()[0].toString());
                    }

                    list.add(discussPost);
                }

                return new AggregatedPageImpl(list,pageable, searchHits.getTotalHits(),
                        searchResponse.getAggregations(),searchResponse.getScrollId(), searchHits.getMaxScore());
            }
        });













    }

}
